﻿using MediatR;
using RedDragon.Common.Domain.MaterialManagements;
using RedDragon.Common.Infrastructure.Interface;
using RedDragon.ERP.API.Application.Commands.MaterialManagements;
using RedDragon.ERP.ErroCodeEnum;
using T.Common.Domain.Common;

namespace RedDragon.ERP.API.Application.Commands.Proccess
{
    /// <summary>
    /// 根据物料ID获取物料规格
    /// </summary>
    public class SearchConditionHandler : IRequestHandler<SearchConditionCommand, Result>
    {
        /// <summary>
        /// 物料服务表仓储
        /// </summary>
        public readonly IBaseRepository<MaterialManagement> _materialManagementRepository;
        /// <summary>
        /// 日志
        /// </summary>
        private readonly ILogger<SearchConditionHandler> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="materialManagementRepository"></param>
        /// <param name="logger"></param>
        public SearchConditionHandler(IBaseRepository<MaterialManagement> materialManagementRepository,
                                      ILogger<SearchConditionHandler> logger)
        {
            _materialManagementRepository = materialManagementRepository;
            _logger = logger;
        }

        /// <summary>
        /// 根据物料ID获取物料规格
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Result> Handle(SearchConditionCommand request, CancellationToken cancellationToken)
        {
            var result = new Result() { Code = (int)CommonErrorCode.Search };
            try
            {
                var query = await (await _materialManagementRepository.GetAll()).FirstAsync(it => it.MaterialId == request.MaterialId);
                if (query != null)
                {
                    result.Code = (int)CommonErrorCode.Success;
                    result.Data = query;
                    result.Msg = "根据物料ID获取物料规格成功";
                }
            }
            catch (Exception ex)
            {
                result.Msg = "根据物料ID获取物料规格异常" + ex.Message;
                _logger.LogError("根据物料ID获取物料规格异常" + ex.Message);
            }
            return result;
        }
    }
}
